import store from '@/store'
import env from 'env.js'

const that = {
	getCookie: (name)=> {
	    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
	    if (arr = document.cookie.match(reg))
	        return unescape(arr[2]);
	    else
	        return null;
	},
	rmCookie: (name) => {
		document.cookie = `${name}=; expires=${new Date(0)}; path=/;`;
	},
	goUrl: (url, isClose) => {
		url = url.indexOf("/pages") < 0 ? "/pages" + url : url
		isClose = isClose || false;
		let action = isClose ? 'redirectTo' : 'navigateTo'
		if (url.indexOf("http") >= 0) {
			url = url.replace("/pages", "")
			uni[action]({
				url: "/pages/goUrl?url=" + encodeURIComponent(url)
			});
		} else if (["/pages/index/index", "/pages/order/order", "/pages/account/account"].indexOf(url) >= 0) {
			uni.switchTab({
				url
			})
		} else {
			uni[action]({
				url
			});
		}
	},
	request: (method, url, data) => {
		if (url.substr(0, 1) === "/") {
			url = url.substr(1)
		}
		let reqUrl = env.domain
		if (url.indexOf("api/") < 0) {
			reqUrl = reqUrl + env.api_server
		}
		reqUrl = reqUrl + url
		return new Promise((rel, reject) => {
			uni.request({
				url: `${reqUrl}`,
				method: method,
				data: data,
				header: {
					openid: that.getCookie("openid"),
				},
				success(res) {
					if (res.data.code === 401) {
						var pages = getCurrentPages()
						var lastPage = pages.length > 0 ? pages[pages.length - 1] : {}
						if (lastPage.route === "pages/account/account") {
							rel(res.data)
						} else {
							that.showMsg("未登录")
							store.commit("common/rmUserInfo")
							store.commit('ask/clearGroups')
							that.goLogin(true)
						}
					} else {
						rel(res.data)
					}
				}
			});
		});
	},
	showMsg: (title, time, icon = 'none') => {
		time = time ? time : 1500
		uni.showToast({
			title: title,
			icon: icon,
		});
		setTimeout(function() {
			uni.hideToast();
		}, time);
	},
	// 上传单图片
	UploadImageRow: (sourceType, quality) => {
		return new Promise((rel, reject) => {
			sourceType = sourceType || ['album']
			quality = quality || 100
			let action = "chooseMedia"
			// #ifdef MP-TOUTIAO
			action = "chooseImage"
			// #endif
			uni[action]({
				count: 1,
				sizeType: ['compressed'],
				sourceType,
				success: (res) => {
					let path = ""
					if (res.tempFiles) {
						path = Array.isArray(res.tempFiles) ? res.tempFiles[0].tempFilePath : res.tempFiles
					}else{
						path = Array.isArray(res.tempFilePaths) ? res.tempFilePaths[0] : res.tempFilePaths
					}
					if (quality == 100) {
						that.uploadOss(path).then(url => {
							rel(url)
						})
					} else {
						uni.compressImage({
							src: path,
							quality,
							success(res) {
								that.uploadOss(path).then(url => {
									rel(url)
								})
							}
						})
					}
				}
			});
		});
	},
	randomString: (len) => {
		len = len || 32;
		var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
		var maxPos = chars.length;
		var str = '';
		for (let i = 0; i < len; i++) {
			str += chars.charAt(Math.floor(Math.random() * maxPos));
		}
		return str;
	},
	GenUuid: (len) => {
		return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
			var r = Math.random() * 16 | 0,
				v = c == 'x' ? r : (r & 0x3 | 0x8);
			return v.toString(16);
		});
	},
	//上传阿里云
	uploadOss: (localPath) => {
		return new Promise((rel, reg) => {
			that.request("get", "/common/oss_sign").then(res => {
				if (res.code !== 10000)
					return uni.showModal({
						title: "提示",
						content: "服务器授权失败",
						showCancel: false
					})
				let upOptions = res.data
				let key = res.data.dir + that.randomString(16)
				if (localPath.indexOf("mp4") >= 0)
					key += ".mp4"
				else
					key += ".jpg"
				let formData = {
					'key': key,
					'policy': upOptions.policy,
					'OSSAccessKeyId': upOptions.accessid,
					'success_action_status': '200',
					'signature': upOptions.signature,
				}
				uni.uploadFile({
					url: upOptions.host,
					filePath: localPath,
					name: 'file',
					formData,
					success: (res) => {
						rel(upOptions.fileUrl + "/" + key)
					},
					complete: (res) => {
						if (res.errMsg.indexOf("uploadFile:fail") >= 0)
							uni.showModal({
								title: "提示",
								content: "上传失败！",
								showCancel: false
							})
					}
				});
			})
		});
	},
	//呼叫号码
	makePhone: (phone) => {
		uni.makePhoneCall({
			phoneNumber: phone
		})
	},
	//复制
	commonCopy: (txt) => {
		uni.setClipboardData({
			data: txt,
			success() {
				that.showMsg("复制成功", 1000, "success")
			},
			fail(res) {
				that.showMsg(res.errMsg)
			}
		})
	},
	//预览图片
	previewImages: (images, current) => {
		current = typeof current === 'number' && !isNaN(current) ? images[current] : current
		uni.previewImage({
			urls: images,
			current
		})
	},
	loginSuccessGo() {
		let userInfo = store.getters["common/getUserInfo"]
		let PrevLoginPath = uni.getStorageSync("PrevLoginPath")
		let url = "/index"
		if (PrevLoginPath)
			url = PrevLoginPath
		uni.removeStorageSync("PrevLoginPath")
		that.goUrl(url, true)
	},
	logout() {
		store.commit('common/rmUserInfo')
	},
	goLogin: (IsCallback) => {
		IsCallback = IsCallback ? IsCallback : false
		if (IsCallback) {
			var pages = getCurrentPages();
			uni.setStorageSync("PrevLoginPath", pages[pages.length - 1].$page.fullPath);
		}
		uni.redirectTo({
			url: "/pages/login"
		})
	},
	pageCallback: (homePage) => {
		let CheckAfterPage = getCurrentPages().length > 1
		if (CheckAfterPage)
			uni.navigateBack({
				delta: 1
			});
		else{
			if(homePage)
				return uni.reLaunch({
					url: homePage
				})
			that.goUrl('/index')
		}
	},
	in_array: (search, array) => {
		return array.includes(search)
	},
}
export default that
